package com.bw.kotlindemo.kotlin.base

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.bw.kotlindemo.kotlin.bean.KBaseBean
import com.bw.kotlindemo.kotlin.bean.KLiveTypeBean
import com.bw.kotlindemo.kotlin.model.KRetrofitManager
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import retrofit2.Call
import retrofit2.Response
import java.lang.reflect.Constructor

/**
 * desc:
 * create by xushaodong on 2023/4/5
 */
open class KBaseViewModel(application: Application) : AndroidViewModel(application) {
    var errorVM = MutableLiveData<String>()
    var toastVM = MutableLiveData<String>()
    var showLoadingVM = MutableLiveData<Boolean>()
    var finishLoadingVM = MutableLiveData<String>()

    /**
     * 测试
     */
    fun test(){


    }

    fun <T : KBaseBean> request(
        block: suspend CoroutineScope.() -> Response<T>,
        success: (T) -> Unit = {},
        error: (String) -> Unit = {}
    ) = viewModelScope.launch {
        kotlin.runCatching {
            block()
        }.onSuccess {
            withContext(Dispatchers.Main) {
                if (it.isSuccessful) {
                    it.body()?.let { it1 -> success(it1) }
                } else {
                    error(it.message())
                }
            }
        }.onFailure {
            withContext(Dispatchers.Main) {
                error("网络异常或数据解析错误")
            }
        }
    }

    protected suspend fun <T> getData(call: Call<T>): Response<T> = withContext(Dispatchers.IO) {
        withContext(Dispatchers.IO){
            call.execute()
        }
    }

    override fun onCleared() {
        super.onCleared()
        //释放一些公共的资源
    }
}